<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/26
 * Time: 16:20
 */

namespace app\index\controller;

use Redis\Redis;
use think\Db;


class OrderInfo extends Common
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 工位列表
     */
    function stationList()
    {
        # 查询门店工位
        $station = Db::table("station s")->field('s.*,s.id work_num')->where(array("biz_id" => $this->bizId))->select();
        foreach ($station as $k => $v) {
            $station[$k]['work_num'] = $k + 1;
            /*工位列表 key:stationlist field: 工位id value:工单id*/
            $order_id = $this->_Redis->hget("stationlist" . $this->bizId, strval($v['id']));
            if (!empty($order_id)) {
                $title = '';
                # 判断是商品还是服务
                if (strstr($order_id, 'orderBiz')) {
                    $order_id = trim(str_replace('orderBiz', '', $order_id));
                    # 查商品工单
                    $order_server = Db::table('order_biz ob')
                        ->field('car_liences,ob.biz_pro_id server_id,custommark,o.order_number')
                        ->join('orders o', 'o.order_number=ob.order_number', 'left')
                        ->where(array('ob.id' => $order_id))
                        ->find();
                    # 获取工单服务名称
                    if (!empty($order_server)) {
                        $title = getsOrderBizProTitle($order_server['server_id'], $order_server['custommark']);
                    } else {
                        # 工位中没有工单(空闲中)
                        $station[$k]['status'] = 0;
                        $station[$k]['stauts'] = 0;
                        continue;
                    }
                } else {
                    # 查询工单信息
                    $order_server = Db::table('order_server os')
                        ->field('car_liences,server_id,custommark,o.order_number')
                        ->join('orders o', 'o.order_number=os.order_number', 'left')
                        ->where(array('os.id' => $order_id))
                        ->find();
                    # 获取工单服务名称
                    if (!empty($order_server)) {
                        $title = getsServerOrCustomsTitle($order_server['server_id'], $order_server['custommark']);
                    } else {
                        # 工位中没有工单(空闲中)
                        $station[$k]['status'] = 0;
                        $station[$k]['stauts'] = 0;
                        continue;
                    }
                }
                $station[$k]['server_name'] = $title;
                $station[$k]['order_server_id'] = $order_id;
                $station[$k]['order_number'] = $order_server['order_number'];
                $station[$k]['car_num'] = $order_server['car_liences'];
                # 查询当前车辆是否绑定会员 or mm.member_level_id = 2
                $bindingInfo = Db::table('member_car mc')
                    ->field("count(mc.id) num ,
(select count(mc.id) from member_car as mc left join member_mapping as mm on mc.member_id = mm.member_id 
where mc.car_licens = '" . $order_server['car_liences'] . "' and (mm.member_level_id = 1 ) and mm.member_expiration >= '" . date('Y-m-d') . "') nums")
                    ->join('member_mapping mm', 'mc.member_id=mm.member_id', 'left')
                    ->where(array('mc.car_licens' => $order_server['car_liences']))
                    ->where("mm.member_level_id > 1 and mc.status != 3")
                    ->find();
                $num = $bindingInfo['num'] + $bindingInfo['nums'];
                if (!empty($bindingInfo) and intval($num) > 0) {
                    # 已绑定
                    $station[$k]['status'] = 1;
                    $station[$k]['stauts'] = 2;
                } else {
                    # 未绑定
                    $station[$k]['status'] = 2;
                    $station[$k]['stauts'] = 1;
                }
            } else {
                # 工位中没有工单(空闲中)
                $station[$k]['status'] = 0;
                $station[$k]['stauts'] = 0;
            }
        }
        return array('status' => true, 'data' => $station);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 获取门店所有工位
     */
    function getStation()
    {
        # 获取redis中工位列表
        //$this->_Redis->delete('getStationList');
        $this->_Redis->hGetJson('getStationList', strval($this->bizId));
        $station = $this->_Redis->hGetJson('getStationList', strval($this->bizId));
        //var_dump($station);
        if (empty($station)) {
            # redis 中为空,查询数据库并存入redis
            $station = Db::table("station")->field(array("id", "station_title"))->where(array("biz_id" => $this->bizId))->select();
            $time = strtotime(date('Y-m-d 23:59:59')) - time();
            $this->_Redis->hSetJson('getStationList', strval($this->bizId), $station, $time);
        }
        if (!empty($station)) {
            $list = $this->_Redis->hGet("stationlist" . $this->bizId);// 获取工位列表的服务状态
            foreach ($station as $k => $v) {
                # 该工位是否可以使用, 是否有服务   false=>不可使用,有服务  true=>可以使用,没有服务
                if (!empty($list[$v['id']])) {
                    $station[$k]['status'] = false;
                } else {
                    $station[$k]['status'] = true;
                }
            }
            return array("status" => true, "data" => $station);
        } else {
            return array("status" => false);
        }
    }

    /**
     * @return array
     * @content 查询服务中、等待中、已完成 数量多少
     */
    function servicesNum()
    {
        # 查询服务中、等待中、已完成 数量多少
        /*$static = Db::query("select count(o.id) all_num,
                                        (select count(o.id) from orders o where o.biz_id = " . $this->bizId . " 
                                        and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1  and (
                                            (select count(os.id) from order_server os where os.order_number=o.order_number and os.status=2)>0
                                             or (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status =4)>0
                                             )) servicing,
                                         (select count(o.id) from orders o where o.biz_id = " . $this->bizId . " 
                                         and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6  and hidden_status = 1 
                                         and (
                                            (
                                            (select count(os.id) from order_server os where os.order_number=o.order_number and (os.status=1 or os.status=5))>0)
                                             or ((select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status =1)>0)
                                             or (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))=0)
                                             ))
                                                waiting,
                                             (select count(o.id) from orders o where o.biz_id =" . $this->bizId . " and (o.order_type=2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1 
                                             and (
                                             (select count(os.id) from order_server os where os.order_number=o.order_number and os.status in (1,2)) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status in (1,4)))=0
                                             and (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))>0)
                                             ) finishIng,
                                        (select count(o.id) from orders o where o.id not in (select o.id from orders o,order_server os where o.biz_id = " . $this->bizId . " 
                                        and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1  and (os.status!=3 and os.status!=4) and os.order_number=o.order_number group by o.id)
                                        and o.biz_id = " . $this->bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6) notFinish
                                        from orders o
                                      where o.biz_id = " . $this->bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1 ");*/
        # 全部
        $all = Db::table('orders o')->where("o.biz_id = " . $this->bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1")->count();
        # 服务中 and (o.order_type = 2 )
        $serving = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $this->bizId . "  and o.order_status = 6 and hidden_status = 1")
            ->where("os.status = 2 or ob.status = 4")
            ->group('o.id')
            ->count('o.id');
        # 等待中 and (o.order_type = 2 )
        $waiting = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $this->bizId . "  and o.order_status = 6 and hidden_status = 1")
            ->where("(os.status=1 or os.status=5) or ob.status = 1 or ((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))=0")
            ->group('o.id')
            ->count('o.id');
        # 已完成 and (o.order_type = 2 )
        $finishIng = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $this->bizId . "  and o.order_status = 6 and hidden_status = 1")
            ->where("(select count(os.id) from order_server os where os.order_number=o.order_number and os.status in (1,2)) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status in (1,4)))=0
                                             and (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))>0")
            ->group('o.id')
            ->count('distinct o.id');
        # 预约的 o.order_status = 6 or
        $operation = Db::table('orders o')
            ->where("o.biz_id = " . $this->bizId . " and o.order_type = 3 and ( o.order_status = 1)")
            ->group('o.id')
            ->count('distinct o.id');
//        dump($static);
        # 查询门店营业状态
        $bizInfo = Db::table('biz')->field('biz_opening start_time,biz_closing end_time,biz_phone phone,open_state')
            ->where(array('id' => $this->bizId))
            ->find();
        # 审核通知
        $redis = new Redis();
        $auditState = $redis->hGet('CooperativeCreation', strval($this->bizId));
        if (empty($auditState)) {
            $audit_notice = 2;
        } else {
            $audit_notice = 1;
        }
        $audit_notice_text = '有新的审核信息';
        if (empty($bizInfo['start_time']) or empty($bizInfo['end_time'])) {
            # 需要设置营业时间
            $set_biz_related = 1;
        } else {
            # 不需要设置
            $set_biz_related = 2;
        }
        return array('status' => true, 'all' => $all, 'serving' => $serving, "waiting" => $waiting, "finishing" => $finishIng, "operation" => $operation,
            'bizInfo' => $bizInfo, 'set_biz_related' => $set_biz_related, 'audit_notice' => $audit_notice, 'audit_notice_text' => $audit_notice_text);
    }

    function setBizRelated()
    {
        # 营业开始时间
        $start_time = input('post.start_time');
        # 营业结束时间
        $end_time = input('post.end_time');
        # 工位数量
        $station_num = input('post.station_num');
        $res = Db::table('biz')->where(array('id' => $this->bizId))
            ->update(array('biz_opening' => $start_time, 'biz_closing' => $end_time));
        if (!$res) {
            return array('status' => false, 'msg' => '系统错误,请联系管理员');
        }
        # 设置工位
        if ($station_num > 0) {
            $station_info = array();
            for ($i = 1; $i <= $station_num; $i++) {
                array_push($station_info, array('biz_id' => $this->bizId, 'station_title' => $i . '号'));
            }
            if (!empty($station_info)) {
                $res = Db::table('station')->insertAll($station_info);
                if (!$res) {
                    return array('status' => false, 'msg' => '系统错误,请联系管理员');
                }
            }
        }
        return array('status' => true, 'msg' => '设置成功');
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 订单列表
     */
    //if(member_id=0,'未注册用户',(select nickname from member m where m.id = o.member_id )) name,
    //if(member_id=0,'',(select member_phone from member m where m.id = o.member_id )) phone,
    //if(member_id=0,'0',(select member_level_id from member_mapping mm where mm.member_id = o.member_id )) levelId,
    //if(member_id=0,'',(select member_expiration from member_mapping mm where mm.member_id = o.member_id )) expiration,
    //if(member_id=0,'',(select member_code from member_mapping mm where mm.member_id = o.member_id )) code,
    function orderList()
    {
        $stationlist = $this->_Redis->hGet("stationlist" . $this->bizId);
        if (empty($stationlist)) {
            $stationlist = makestation($this->bizId);
        }

        $stationkey = array_keys($stationlist); # 取出工位id 组成新的数组
        if (input('post.mark') == 'test') {
            //$this->_Redis->hDel("stationlist" . $this->bizId,1);
            //$this->_Redis->hDel("stationlist" . $this->bizId,5);
            //$this->_Redis->hDel("stationlist" . $this->bizId,7);
            //$this->_Redis->hDel("stationlist" . $this->bizId,8);
            dump($stationlist);

            dump($stationkey);
        }
        # 接收查询状态(等待中:1,服务中:2,已完成:4  预约:5)
        $_status = input('post.status') ?? 1;
        $_wait_status = '';
        if ($_status == 1) {
            # 等待中
            $_statusBiz = 1;
            $_wait_status = " and o.order_status != 1 and ( (select count(os.id) from order_server os where os.order_number=o.order_number and (os.status=1 or os.status=5))>0 
 or  ((select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status =1)>0) 
 or (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))=0)";
        }
        if ($_status == 2) {
            # 服务中
            $_statusBiz = 4;
            $_wait_status = " and o.order_status != 1 and ((select count(os.id) from order_server os where os.order_number = o.order_number and os.status = {$_status})>0
        or (select count(ob.id) from order_biz ob where ob.order_number = o.order_number and ob.status={$_statusBiz}) >0 ";
        }
        if ($_status == 4) {
            # 已完成
            $_statusBiz = 2;
            $_wait_status = "  and o.order_status != 1 and (((select count(os.id) from order_server os where os.order_number=o.order_number and os.status in (1,2)) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status in (1,4)))=0) 
              and o.id not in 
                                        (select o.id from orders o where 
                                        (((select count(os.id) from order_server os where os.order_number=o.order_number)>0
                                         and (select count(os.id) from order_server os where os.order_number=o.order_number and os.status !=4 and os.status !=6 )>0)
                                          or
                                        (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status != 2 and ob.status != 1)>0)
                                        )
                                        and (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))>0 
                                        ";
        }
        if ($_status == 5) {
            # 预约的订单
            $_statusBiz = 2;
            $_wait_status = " and o.order_type = 3 and  (o.order_status = 1";
        }
        /* # 将状态修改为3 并且预约时间+30分钟仍然超时的订单，为未到店订单,并修改结束时间  o.lineup,
         Db::table('orders')
             ->where("id != 0 and order_type = 3 and biz_id = " . $this->bizId . " and order_status = 1 and order_appoin_time <= '" . date('Y-m-d H:i:s', strtotime('-30 minutes')) . "'")
             ->update(array('order_status' => 3, 'order_over' => date('Y-m-d H:i:s')));*/
        if (!empty($this->bizId)) {
            # 查询订单列表  o.order_create order_time,order_appoin_time
            $orderInfo = Db::query("select o.id order_id,(o.order_price-o.voucher_price) order_price,
			order_create time_order,
if((select count(id) from member_car where status != 3 and car_licens = o.car_liences and queue_status = 1)>=1,1,0) lineup,
 o.order_number,o.car_liences car_num,os.custommark,os.status,
order_create order_time,o.hidden_status,o.member_id,
o.member_car_id,o.car_mileages carMileage,o.biz_pro_id,o.biz_type,1 searchType,o.order_type,o.order_status,o.biz_pro_id,o.pay_price,o.order_appoin_time,o.arrive_time,
member_level_id,member_integral integral, convert(member_balance,DECIMAL(10,2)) balance, member_expiration, member_code,
if(o.member_car_id=0,o.car_level,(select `level` from car_sort cs  right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) car_level,
if(o.member_car_id=0,(select sort_title from car_sort cs where cs.id = o.car_sort),(select sort_title from car_sort cs right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) sort_title,
if(o.member_car_id=0,(select title from car_logo cl where cl.id = o.car_logo),(select title from car_logo cl right join car_sort cs on cs.logo_id = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) logo_title,
if(o.member_car_id=0,(select level_title from car_level cl where cl.id = o.car_level),(select level_title from car_level cl right join car_sort cs on cs.level = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) carType,
if(o.member_id = 0,'普通用户',(select level_title from member_level ml where ml.id = mm.member_level_id)) vipGrade,
if(o.member_id = 0,'',(select member_phone from member m where m.id = o.member_id)) phone,
(select count(os.id) from order_server os where os.status = 1 and os.order_number = o.order_number) waiting,
(select count(os.id) from order_server os where os.status = 2 and os.order_number = o.order_number) serving,
(select station_id from order_server os where os.status = 2 and os.order_number = o.order_number limit 1) stationId,
(select count(os.id) from order_server os where os.status = 4 and os.order_number = o.order_number) complete,
(select count(ob.id) from order_biz ob where ob.status != 2 and ob.order_number = o.order_number) bizCount,
(select if(os.custommark = 1,(select service_title from service s where s.id = os.server_id limit 1),(select custom_server_title from customserver cs where cs.id = os.server_id limit 1)) from order_server os where os.order_number = o.order_number and os.status = " . $_status . " limit 1) waitService,
(select os.id from order_server os where os.order_number = o.order_number and os.status = " . $_status . " limit 1) waitServiceId 
from orders o 
left join order_server os on os.order_number = o.order_number 
left join order_biz ob on ob.order_number = o.order_number 
left join member_mapping mm on mm.member_id = o.member_id 
where biz_id = " . $this->bizId . " and (order_type = 2 or order_type = 3) and hidden_status = 1 

and (order_status = 1 or order_status = 2 or order_status = 3 or order_status = 6) 
" . $_wait_status . ") 
group by o.order_number 

order by order_status desc, lineup desc,order_type desc, time_order asc, o.id asc");
            //and if(order_type=3,date_format(order_appoin_time,'%Y-%m-%d') <= '" . date('Y-m-d') . "',date_format(order_create,'%Y-%m-%d') <= '" . date('Y-m-d') . "')
//var_dump(Db::table('orders')->getLastSql());
//order by date_format(order_create,'%Y-%m-%d') asc, order_type desc,order_appoin_time,lineup desc,o.id asc");
            # 查询个状态数量
            $serviceNum = $this->servicesNum();
            if (!empty($orderInfo)) {
                foreach ($orderInfo as $k => $v) {
                    $orderInfo[$k]['status'] = $_status;
                    $orderInfo[$k]['status_second'] = $_status;
                    $num = $v['waiting'] + $v['serving'] + $v['bizCount'];
                    if (intval($num) > 0) {
                        $orderInfo[$k]['payStatus'] = 0;
                    } else {
                        if (empty($v['sort_title']))
                            $orderInfo[$k]['payStatus'] = 2;
                        else
                            $orderInfo[$k]['payStatus'] = 1;
                    }
                    $orderInfo[$k]['brand_model'] = $v['sort_title'] . "-" . $v['logo_title'] . "-" . $v['carType'];
                    if (is_null($v['waitService'])) {
                        $orderInfo[$k]['waitService'] = '等待中';
                    }
                    if (is_null($v['carType'])) {
                        $orderInfo[$k]['carType'] = '-';
                    }
                    # 查询等待中/服务中/已完成/的服务
                    if ($_status != 5) {
                        # 状态为 等待中/服务中/已完成
                        $_waitService = Db::query("select os.id,1 searchType, if(os.custommark = 1,(select service_title from service s where s.id = os.server_id limit 1),
(select custom_server_title from customserver cs where cs.id = os.server_id limit 1)) title 
from order_server os where os.order_number = '" . $v['order_number'] . "' and os.status = " . $_status);
                    } else {
                        # 状态为  预约 单独查询
                        $_waitService = Db::query("select os.id,1 searchType, if(os.custommark = 1,(select service_title from service s where s.id = os.server_id limit 1),
(select custom_server_title from customserver cs where cs.id = os.server_id limit 1)) title,os.status  
from order_server os where os.order_number = '" . $v['order_number'] . "'");
                    }
                    if (!empty($_waitService)) {
                        $orderInfo[$k]['serviceInfo'] = $_waitService;
                        if ($_status == 5) {
                            $orderInfo[$k]['status'] = $_waitService[0]['status'];
                            $orderInfo[$k]['waitServiceId'] = $_waitService[0]['id'];
                            $orderInfo[$k]['waitService'] = $_waitService[0]['title'];
                        }
                    } else {
                        $_info = Db::query("select ob.id,2 searchType,if(ob.custommark = 1,(select biz_pro_title from biz_pro b where b.id = ob.biz_pro_id limit 1),
(select custom_biz_title from custom_biz cb where cb.id = ob.biz_pro_id limit 1)) title 
from order_biz ob where ob.order_number = '" . $v['order_number'] . "' and ob.status = " . $_statusBiz);
                        if (!empty($_info)) {
                            # 商品(默认为服务)
                            $orderInfo[$k]['searchType'] = 2;
                        }
                        $_waitServiceId = Db::query("select ob.id,custommark,station_id,count(id) num 
from order_biz ob where ob.order_number = '" . $v['order_number'] . "' and ob.status = " . $_statusBiz . " limit 1");
                        $orderInfo[$k]['waiting'] = $_waitServiceId[0]['num'];
                        $orderInfo[$k]['waitServiceId'] = $_waitServiceId[0]['id'];
                        $orderInfo[$k]['custommark'] = $_waitServiceId[0]['custommark'];
                        $orderInfo[$k]['stationId'] = $_waitServiceId[0]['station_id'];
                        if (!empty($_info)) {
                            $orderInfo[$k]['waitService'] = $_info[0]['title'];
                            $orderInfo[$k]['serviceInfo'] = $_info;
                        } else {
                            $orderInfo[$k]['serviceInfo'] = array();
                        }
                    }
                    # 查询当前车辆是否绑定会员
                    $bindingInfo = Db::query("select count(mc.id) as num ,
(select count(mc.id) from member_car as mc left join member_mapping as mm on mc.member_id = mm.member_id 
where mc.car_licens = '" . $v['car_num'] . "' and (mm.member_level_id = 1 ) and mm.member_expiration >= '" . date('Y-m-d') . "') as nums 
from member_car as mc left join member_mapping as mm on mc.member_id = mm.member_id where mc.car_licens = '" . $v['car_num'] . "' and mc.status != 3 and mm.member_level_id > 1");
                    $num = $bindingInfo[0]['num'] + $bindingInfo[0]['nums'];
                    if (!empty($bindingInfo) and intval($num) > 0) {
                        $orderInfo[$k]['bindinginfo'] = "已绑定会员";
                        $orderInfo[$k]['bind_status'] = true;
                    } else {
                        $orderInfo[$k]['bindinginfo'] = "未绑定会员";
                        $orderInfo[$k]['bind_status'] = false;
                    }
                    # 订单总金额
//                        $orderInfo[$k]['totalPrice'] = floatval(getsOrderPrice($v['order_number']));
                    if ($v['order_type'] == 3) {
                        # 预约订单,根据orders表中的biz_pro_id查询服务名称
                        if ($v['order_status'] == 1) {
                            # 预约还未到店
                            $orderInfo[$k]['bookingStatus'] = 1;
                            $orderInfo[$k]['searchType'] = 3;
                            $orderInfo[$k]['bookingId'] = $v['biz_pro_id'];
                            $orderInfo[$k]['bookingPrice'] = $v['pay_price'];
                            $orderInfo[$k]['waitService'] = getServerTitle($v['biz_pro_id']);
                            //$orderInfo[$k]['waitService'] = '未到店';
                            $orderInfo[$k]['order_create'] = $v['order_appoin_time'];
                        } elseif ($v['order_status'] == 3) {
                            # 已超时
                            $orderInfo[$k]['bookingStatus'] = 3;
                            $orderInfo[$k]['searchType'] = 4;
                            $orderInfo[$k]['bookingId'] = $v['biz_pro_id'];
                            $orderInfo[$k]['bookingPrice'] = $v['pay_price'];
                            $orderInfo[$k]['waitService'] = getServerTitle($v['biz_pro_id']);
                            //$orderInfo[$k]['waitService'] = '已超时';
                            $orderInfo[$k]['order_create'] = $v['order_appoin_time'];
                        } else {
                            # 正常
                            $orderInfo[$k]['bookingStatus'] = 0;
                            $orderInfo[$k]['order_create'] = $v['arrive_time'];
                        }
                    } else {
                        $orderInfo[$k]['bookingStatus'] = 0;
                    }
                    if (!empty($orderInfo[$k]['stationId'])) {
                        $station_index = array_search($orderInfo[$k]['stationId'], $stationkey);
                        $orderInfo[$k]['station_index'] = intval($station_index) + 1;
                    }
                    # 存入redis
                }
                if (!empty($orderInfo))
                    return array('status' => true, 'info' => $orderInfo, 'service_num' => $serviceNum);
                else
                    return array('status' => false, 'msg' => '订单为空', 'info' => array(), 'service_num' => $serviceNum);
            } else {
                return array('status' => false, 'msg' => '订单为空', 'info' => array(), 'service_num' => $serviceNum);
            }
        } else {
            return array('status' => false, 'msg' => '门店id为空', 'info' => array());
        }
    }

    /**
     * @return float|string
     * @content 超时订单数量
     */
    function overtimeOrders()
    {
        $num = Db::table('orders')->where(array('order_status' => 3, 'biz_id' => $this->bizId))->count();
        return $num;
    }

    /**
     * @return array
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 未到店
     */
    function notInStore()
    {
        # 接收订单编号
        $order_number = input('post.order_number');
        $res = TimeTask::notInStore($order_number, 1);
        return $res;
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 订单详情
     */
    function orderDetail()
    {
        # 接收订单编号
        $orderNumber = input('post.order_number');
        if (!empty($orderNumber)) {
//            $payment = new Payment();
//            $payment->WriteOrderPrice(true, $orderNumber);
            $stationlist = $this->_Redis->hGet("stationlist" . $this->bizId);
            if (empty($stationlist)) {
                $stationlist = makestation($this->bizId);
            }
            $stationkey = array_keys($stationlist); # 取出工位id 组成新的数组
            # 从redis中获取
            $orderInfo = $this->_Redis->hGetJson('orderInfo', $orderNumber);
            if (empty($orderInfo)) {
                # 查询订单基本信息,用户信息
                //if(o.member_car_id=0,'未注册用户',(select (nickname) from member m where m.id = o.member_id )) name,
                $orderInfo = $this->getOrderInfo($orderNumber);
            }
            # 查询商品工单
            $orderBiz = Db::table('order_biz ob')
                ->field("ob.id,ob.referrer,ob.employee_id,2 orderType,status,(ob.pro_price - ob.coupon_price) price,ob.bizpro_number num,coupon_mark,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,ob.referrer)) referrer_name,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,ob.employee_id)) employee_name,
                if(ob.custommark=1,'系统商品','自定义商品') type,
                if(ob.custommark = 1,(select biz_pro_title from biz_pro bp where bp.id = ob.biz_pro_id limit 1),
                (select custom_biz_title from custom_biz cb where cb.id = ob.biz_pro_id limit 1)) title,
                case ob.status 
                      when 1 then '等待中'
                      when 2 then '已完成'
                      when 3 then '已完成'
                      when 4 then '服务中'
                end serviceStatus,
                if(station_id is null,'',(select station_title from station s where s.id = ob.station_id)) workNums,
                if(station_id is null,'',station_id) workNum ")
                ->where(array('order_number' => $orderNumber))
                ->buildSql();
            # 查询服务工单
            $orderServer = Db::table('order_server os')
                ->field("os.id,os.referrer,os.employee_id,1 orderType,status,os.price,1 num,coupon_mark,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,os.referrer)) referrer_name,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,os.employee_id)) employee_name,
                if(os.custommark=1,'系统服务','自定义服务') type,
                if(os.custommark=1,(select service_title from service s where s.id=os.server_id limit 1),
                   (select custom_server_title from customserver cs where cs.id=os.server_id limit 1)) title,
                   case status
                        when 1 then '未开始'
                        when 2 then '服务中'
                        when 3 then '已完成'
                        when 4 then '已完成'
                        when 5 then '等待中'
                        when 6 then '已完成'
                   end serviceStatus,
                   if(station_id is null,'',(select station_title from station s where s.id = os.station_id)) workNums,
                   if(station_id is null,'',station_id) workNum 
                ")
                ->where(array('order_number' => $orderNumber))
                ->union([$orderBiz])
                ->buildSql();
            $orderDetail = Db::table($orderServer . 'tem')->select();
            if (!empty($orderDetail)) {
                foreach ($orderDetail as $k => $v) {
                    if ($v['coupon_mark'] == 2) {
                        $orderDetail[$k]['serviceStatus'] = '已核销';
                    }
                    if (!empty($v['workNum'])) {
                        $station_index = array_search($v['workNum'], $stationkey);
                        $orderDetail[$k]['station_index'] = intval($station_index) + 1;
                    } else {
                        $orderDetail[$k]['station_index'] = '';
                    }
                }
            }
            $car_info = Db::table('member_car mc')
                ->field('car_licens car_num,car_mileage mileage,cs.sort_title,cl.title logo_title,cle.level_title,cs.level,cs.logo_id,mc.car_type_id')
                ->join('car_sort cs', 'cs.id=mc.car_type_id', 'left')
                ->join('car_logo cl', 'cl.id=cs.logo_id', 'left')
                ->join('car_level cle', 'cle.id=cs.level', 'left')
                ->where(array('car_licens' => $orderInfo['carNum']))
                ->find();
            if (empty($car_info)) {
                $car_info = array(
                    'car_num' => $orderInfo['carNum'],
                    'mileage' => $orderInfo['carMileage'],
                    'logo_id' => $orderInfo['logo_id'],
                    'car_type_id' => $orderInfo['car_sort'],
                    'level' => $orderInfo['car_level']
                );
            }
            /* if($orderNumber=='20210609104021303100012'){
                 dump($orderInfo);
                 dump($orderDetail);
                 dump($car_info);die;
             }*/
            return array('status' => true, 'data' => array('orderInfo' => $orderInfo, 'orderDetail' => $orderDetail, 'car_info' => $car_info));
        } else {
            return array('status' => false, 'msg' => '订单编号为空');
        }
    }

    function getOrderInfo($orderNumber)
    {
        $orderInfo = Db::table('orders o')
            ->field("o.id order_id,o.order_number,o.car_liences carNum,o.member_id,o.member_car_id,o.biz_pro_id,o.biz_type,
o.order_create,o.order_type,o.order_status,o.biz_pro_id,o.pay_price,o.order_appoin_time,o.arrive_time,o.car_level,o.car_sort,o.car_logo logo_id,
if(o.member_car_id=0,o.car_level,(select `level` from car_sort cs  right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) car_level,
if(o.member_car_id=0,(select sort_title from car_sort cs where cs.id = o.car_sort),
  (select sort_title from car_sort cs right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) sort_title,
if(o.member_car_id=0,(select title from car_logo cl where cl.id = o.car_logo),
  (select title from car_logo cl right join car_sort cs on cs.logo_id = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) logo_title,
if(o.member_car_id=0,(select level_title from car_level cl where cl.id = o.car_level),
  (select level_title from car_level cl right join car_sort cs on cs.level = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) carType,

if(o.member_id = 0,'普通用户',(select level_title from member_level ml where ml.id = mm.member_level_id)) vipGrade,
if(o.member_id = 0,'',(select member_phone from member m where m.id = o.member_id)) phone,
if(car_mileages is not null,car_mileages,(select if(mc.car_mileage is null,0,car_mileage) from member_car mc where mc.car_licens = o.car_liences limit 1)) carMileage,
(coalesce((select sum(os.price) from order_server os where os.order_number=o.order_number),0)+
 coalesce((select sum(ob.pro_price) from order_biz ob where ob.order_number = o.order_number),0)-
 coalesce((select sum(ob.coupon_price) from order_biz ob where ob.order_number=o.order_number and ob.status=2 and ob.coupon_mark =1),0) -
 coalesce((select voucher_price from log_cashcoupon lc where lc.voucher_type != 3 and lc.voucher_type != 4 and lc.voucher_type != 7 and lc.voucher_type != 8 
        and lc.order_number=o.order_number),0)) countPrice,
        o.order_price ,
member_level_id,member_integral integral, convert(member_balance,DECIMAL(10,2)) balance, member_expiration, member_code")
            ->where(array('order_number' => $orderNumber, 'biz_id' => $this->bizId))
            ->join('member_mapping mm', 'mm.member_id=o.member_id', 'left')
            ->find();
        if (!empty($orderInfo['sort_title'])) {
            $orderInfo['carInfo'] = $orderInfo['sort_title'] . "-" . $orderInfo['logo_title'] . "-" . $orderInfo['carType'];
        }
        if ($orderInfo['order_type'] == 3) {
            if ($orderInfo['order_status'] == 1) {
                # 预约还未到店
                $orderInfo['bookingStatus'] = 1;
            } elseif ($orderInfo['order_status'] == 3) {
                # 已超时
                $orderInfo['bookingStatus'] = 3;
            } else {
                # 正常
                $orderInfo['bookingStatus'] = 0;
            }
        } else {
            $orderInfo['bookingStatus'] = 0;
        }
        if ($orderInfo['order_status'] == 5)
            # 存入redis(已完成的订单)
            $this->_Redis->hSetJson('orderInfo', $orderNumber, $orderInfo);
        return $orderInfo;
    }

    /**
     * @return array|mixed|string
     * @throws \BaseException
     * @content 拍照识别
     */
    function photoRecognition()
    {
        $imgInfo = input('post.img_info');
        if (empty($imgInfo)) {
            return array('status' => false, 'msg' => '请上传图片');
        }
        $imgUrl = uploadBase($imgInfo);
        if (is_array($imgUrl)) {
            return $imgUrl;
        }
        # 车牌识别
        $cardType = 19;
        $mark = input('post.mark');
        if ($mark == 'vin') {
            # VIN识别
            $cardType = 2007;
        }
        $res = ThirdParty::certificates(ROOT_PATH . "upload/" . $imgUrl, $cardType);
        # 删除图片
        delImgInfo($imgUrl);
        return $res;

    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 车辆到店(输入车牌号,判断是否存在订单信息: 存在->去订单详情页,不存在->返回车辆信息)
     */
    function carCome()
    {
        # 接收车牌号
        $carNum = strtoupper(input('post.car_num'));
        if (!empty($carNum)) {
            $order_number = '';
            # 当前是否存在订单状态(默认不存在)
            $orderExists = false;
            # 判断订单状态 (1 等待中 2服务中 4已完成 5线上订单(预约))
            $orderExists_status = 1;
            # 查询该车牌号是否有未结算的订单
            $orderInfo = Db::table('orders')
                ->field('id,order_number,order_type,order_status')
                ->where(array('car_liences' => $carNum))
                ->where(array('biz_id' => $this->bizId))
                ->where("order_status != 5 and order_status != 7 and order_status != 4")
                ->order(array('id' => 'asc'))
                ->find();
            # 查询车辆信息
            $_return = Db::table('member_car mc')
                ->field('car_licens car_num,car_mileage mileage,cs.sort_title,cl.title logo_title,cle.level_title,cs.level,cs.logo_id,mc.car_type_id')
                ->join('car_sort cs', 'cs.id=mc.car_type_id', 'left')
                ->join('car_logo cl', 'cl.id=cs.logo_id', 'left')
                ->join('car_level cle', 'cle.id=cs.level', 'left')
                ->where(array('car_licens' => $carNum))
                ->where("status != 3")
                ->find();
            if (empty($_return)) {
                $_return['car_num'] = $carNum;
                $_return['mileage'] = 0;
                $_return['isExist'] = 0;
            } else {
                $_return['isExist'] = 1;
            }
            if (!empty($orderInfo)) {
                $orderType = $orderInfo['order_type'];
                # 当前存在订单,直接跳转订单详情页面
                $orderExists = true;
                $order_number = $orderInfo['order_number'];
                if ($orderInfo['order_type'] == 3 and $orderInfo['order_status'] == 1) {
                    $orderExists_status = 5;
                } else {
                    # 根据工单中的服务状态来进行判断
                    $orderServer = Db::table('order_server')->field('status')->where(array('order_number' => $order_number))->find();
                    if (empty($orderServer) or (!empty($orderServer) and ($orderServer['status'] == 1 or $orderServer['status'] == 5))) {
                        $orderExists_status = 1;
                    } else {
                        if ($orderServer['status'] == 2 and $orderInfo['order_status'] == 6) {
                            $orderExists_status = 2;
                        } else {
                            $orderExists_status = 4;
                        }
                    }
                }
            } else {
                $orderType = '';
                # 查询该车辆是否有绑定的会员信息
                $bindInfo = Db::table('member_car mc')
                    ->field("count(mc.id) m,
                    (select count(mc.id) from member_car mc left join member_mapping mm on mm.member_id=mc.member_id
                     where mc.car_licens='" . $carNum . "' and (mm.member_level_id =1) and mm.member_expiration >= '" . date('Y-m-d') . "') n")
                    ->join('member_mapping mm', 'mc.member_id=mm.member_id', 'left')
                    ->where(array('mc.car_licens' => $carNum))
                    ->where("status != 3")
                    ->where("mm.member_level_id > 1")
                    ->find();
                if (!empty($bindInfo)) {
                    if ((intval($bindInfo['m']) + intval($bindInfo['n']))) {
                        $_return['bindInfo'] = '已绑定会员';
                        $_return['bind_status'] = true;
                    } else {
                        $_return['bindInfo'] = '未绑定会员';
                        $_return['bind_status'] = false;
                    }
                } else {
                    $_return['bindInfo'] = '未绑定会员';
                    $_return['bind_status'] = false;
                }
            }
            // $_return['lineup'] = getsLineUp($carNum, $this->bizId);
            $lineUp = Db::table('member_car')->where(array('car_licens' => $carNum, 'queue_status' => 1))->where('member_id != 0 and member_id is not null and status != 3')->count();
            $_return['lineup'] = $lineUp >= 1 ? 1 : 0;
            return array('status' => true, 'orderExists' => $orderExists, 'orderExists_status' => $orderExists_status, 'data' => array('info' => $_return, 'order_type' => $orderType, 'order_number' => $order_number));
        } else {
            # 车牌号为空
            return array('status' => false, 'msg' => '车牌号为空');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 修改车辆信息
     */
    function writeCarInfo()
    {
        # 接收要修改的车牌号
        $carNum = strtoupper(input('post.car_num'));
        # 接收要修改的车辆品牌id
        $logoId = input('post.logo_id');
        # 接收要修改的车辆系列id
        $sortId = input('post.sort_id');
        # 接收要修改的车辆等级
        $carLevel = input('post.level');
        # 接收原来的车辆等级
        $oldLevel = input('post.old_level');
        # 接收订单编号
        $orderNumber = input('post.order_number');
        if (!empty($carNum) and !empty($logoId) and !empty($sortId) and !empty($carLevel) and $orderNumber != 'undefined') {
            # 根据车牌号修改车辆信息
            Db::table('member_car')
                ->where(array('car_licens' => $carNum))
                ->update(array('car_type_id' => $sortId));
            # 判断是否存在订单(存在修改车辆信息,重新计算价格,不存在创建订单)
            if (!empty($orderNumber)) {
                # 修改订单中的车辆信息
                Db::table('orders')->where(array('order_number' => $orderNumber))
                    ->where("order_status !=5 and (order_type =2 or order_type=3)")
                    ->update(array('car_level' => $carLevel, 'car_logo' => $logoId, 'car_sort' => $sortId));
                # 判断车辆等级是否发生改变,改变了需要重新计算订单的价格
//                if ($carLevel != $oldLevel) {
                # 调用重新计算价格的方法
                $payment = new Payment();
                $payment->WriteOrderPrice(true, $orderNumber);
//                }
            } else {
                # 创建新订单
                $orderNumber = getOrderNumber($this->bizId);
                $_array = array(
                    'order_status' => 6,
                    'biz_id' => $this->bizId,
                    'order_type' => 2,
                    'biz_pro_id' => 0,
                    'order_create' => date('Y-m-d H:i:s', time()),
                    'order_number' => $orderNumber,
                    'biz_type' => 2,
                    'car_liences' => $carNum,
                    'car_level' => $carLevel,
                    'car_logo' => $logoId,
                    'car_sort' => $sortId,
                    'lineup' => getsLineUp($carNum, $this->bizId)
                );
                Db::table('orders')->insert($_array);
            }
            return array('status' => true, 'data' => array('order_number' => $orderNumber));
        } else {
            return array('status' => false, 'msg' => '参数有误');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 修改车辆公里数
     */
    function writeCarMileage()
    {
        # 要修改的车牌号
        $carNum = strtoupper(input('post.car_num'));
        # 要修改的车辆公里数
        $mileage = input('post.mileage');
//        # 订单编号
//        $orderNumber = input('post.order_number');
//        and $orderNumber != 'undefined'
        if (!empty($carNum) and !empty($mileage)) {
            # 修改用户车辆公里数
            Db::table('member_car')->where(array('car_licens' => $carNum))->update(array('car_mileage' => $mileage));
            # 判断是否存在订单(存在,修改订单中的公里数)
//            if (!empty($orderNumber) and $orderNumber != 'undefined') {
//            ->where(array('order_number' => $orderNumber))
            # 订单未结算的
            Db::table('orders')
                ->where("order_status != 5 and order_status != 7")
                ->where(array('car_liences' => $carNum))
                ->update(array('car_mileages' => $mileage));
//            }
            return array('status' => true);
        } else {
            return array('status' => false, 'msg' => '参数有误');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 订单绑定手机号(同时更新该订单下的服务和商品的价格,车辆信息)
     */
    function bindPhone()
    {
        # 接收手机号
        $phone = trim(input("post.phone"));
        # 接收订单编号
        $order_number = input("post.order_number");
        if (!empty($phone) and !empty($order_number)) {
            # 判断手机号是否正确
            if (!CheckMobile($phone)) {
                return array('status' => false, 'msg' => '手机号输入不正确');
            }
            # 查询该订单是否绑定了车辆信息
            $orders = Db::table("orders")
                ->field("car_liences,member_car_id,car_level,car_logo,car_sort,car_mileages,member_id")
                ->where(array("order_number" => $order_number))->find();
//            if (!empty($orders['car_level']) and !empty($orders['car_logo']) and !empty($orders['car_sort'])) {
            # 查询该用户是否存在
            $member = Db::table('member m')
                ->field('m.id,mm.member_level_id,mm.member_expiration,mm.member_code')
                ->join('member_mapping mm', 'm.id=mm.member_id', 'left')
                ->where(array('m.member_phone' => $phone))
                ->find();
            if (empty($member)) {
                # 删除上一个用户的信息和车
                if (!empty($orders['member_id'])) {
                    $newMember = $this->_Redis->hGet('cooperation_newMember', $order_number);
                    if (!empty($newMember)) {
                        Db::table('member')->where(array('id' => $orders['member_id']))->delete();
                        Db::table('member_mapping')->where(array('id' => $newMember))->delete();
                        Db::table('member_car')->where(array('id' => $orders['member_car_id']))->delete();
                        $this->_Redis->hDel('cooperation_newMember', $order_number);
                    }
                }
                # 新用户注册用户及车辆信息
                $member_id = Db::table('member')->insertGetId(array('member_phone' => $phone));
                $member_mapping_id = Db::table('member_mapping')->insertGetId(array('member_id' => $member_id, 'member_create' => date('Y-m-d H:i:s')));
                # 清空其他人的车
//                Db::table('member_car')->where(array('car_licens' => $orders['car_liences']))->update(array('status' => 3));
                # 用户添加一辆车
                $memberCarId = Db::table('member_car')->insertGetId(array(
                    'car_licens' => $orders['car_liences'],
                    'car_type_id' => $orders['car_sort'],
                    'member_id' => $member_id
                ));
                $this->_Redis->hSet('cooperation_newMember', $order_number, $member_mapping_id);
                $memberLevelId = 0;
                $memberExpiration = '';
                $memberCode = '';
            } else {
                $member_id = $member['id'];
                $memberLevelId = $member['member_level_id'];
                $memberExpiration = $member['member_expiration'];
                $memberCode = $member['member_code'];
                # 用户已注册判断该车辆是否为该用户已绑定车辆
                $member_car = Db::table('member_car')->field('id')
                    ->where(array('member_id' => $member_id, 'car_licens' => strtoupper($orders['car_liences'])))->where("status != 3")->find();
                if (!empty($member_car)) {
                    # 该车绑定了该用户
                    $memberCarId = $member_car['id'];
                } else {
                    # 查询用户共绑了几辆车
                    $carCount = Db::table("member_car")->field('id')->where(array("member_id" => $member_id))->where("status != 3")->count();
                    # 判断是不是会员 , 不是会员 ,随便加车,
                    if ($carCount >= 1) {
                        if ($memberLevelId > 1) {
                            # 多辆车
                            return array("status" => false, "msg" => "请用户自行注册该车辆");
                        } else {
                            # 判断是不是体验卡会员
                            if (($memberLevelId == 1) and $memberExpiration >= date('Y-m-d')) {
                                return array("status" => false, "msg" => "请用户自行注册该车辆");
                            }
                        }
                    }
                    # 清空其他人的车
                    Db::table('member_car')->where(array('car_licens' => $orders['car_liences']))->where("member_id != " . $member_id)->update(array('status' => 3));
                    $memberCar = Db::table('member_car')->field('id')
                        ->where(array('member_id' => $member_id, 'car_licens' => strtoupper($orders['car_liences']), 'status' => 3))->find();
                    if (!empty($memberCar)) {
                        Db::table('member_car')->where(array('id' => $memberCar['id']))->update(array(
                            'car_licens' => strtoupper($orders['car_liences']),
                            'car_type_id' => $orders['car_sort'],
                            'member_id' => $member_id,
                            'status' => 1
                        ));
                        $memberCarId = $memberCar['id'];
                    } else {
                        # 直接给该用户添加一辆车
                        $memberCarId = Db::table('member_car')->insertGetId(array(
                            'car_licens' => strtoupper($orders['car_liences']),
                            'car_type_id' => $orders['car_sort'],
                            'member_id' => $member_id
                        ));
                    }
                }
                # 删除上一个用户的信息和车
                if (!empty($orders['member_id']) and $orders['member_id'] != $member_id) {
                    $newMember = $this->_Redis->hGet('cooperation_newMember', $order_number);
                    if (!empty($newMember)) {
                        Db::table('member')->where(array('id' => $orders['member_id']))->delete();
                        Db::table('member_mapping')->where(array('id' => $newMember))->delete();
                        Db::table('member_car')->where(array('id' => $orders['member_car_id']))->delete();
                        $this->_Redis->hDel('cooperation_newMember', $order_number);
                    }
                }
            }
            if ($member_id != 0 and $memberCarId != 0) {
                # 修改订单的绑定人和车
                Db::table('orders')->where(array('order_number' => $order_number))
                    ->update(array('member_id' => $member_id, 'member_car_id' => $memberCarId));
                # 更改服务工单,商品工单中的价格
                $payment = new Payment();
                $payment->WriteOrderPrice(false, $order_number, $memberLevelId, $memberExpiration, $memberCode, $orders['car_level']);

                if (!empty($orders['car_mileages'])) {
                    # 修改车辆公里数
                    Db::table('member_car')->where(array('car_licens' => strtoupper($orders['car_liences'])))
                        ->update(array('car_mileage' => $orders['car_mileages']));
                }
                return array("status" => true, 'data' => array('member_id' => $member_id, 'member_level_id' => $memberLevelId, 'totalPrice' => floatval(getsOrderPrice($order_number))));
            }
//            } else {
//                return array("status" => false, "msg" => "请完善车辆信息");
//            }
        } else {
            return array('status' => false, 'msg' => '手机号/订单编号为空');
        }
    }

    /**
     * @return array
     * @content 查询该订单各支付方式的支付价格
     */
    function checkPayPrice()
    {
        # 订单编号
        $order_number = input('post.order_number');
        # 用户id
        $memberId = input('post.member_id') ?? 0;
        if (empty($order_number)) {
            return array('status' => false, 'msg' => '订单编号为空');
        }
        # 查询车型
        $carLevel = Db::table('orders')->field('car_level')->where(array('order_number' => $order_number))->value('car_level');
        if (empty($carLevel)) {
            return array('status' => false, 'msg' => '请完善车辆信息');
        }
        # 查询支付金额
        $payment = new Payment();
        $res = $payment->countPay($this->bizId, $order_number, $memberId,input('post.mark'));
        $res['order_info'] = $this->getOrderInfo($order_number);
        return $res;
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 订单支付
     */
    function ordersPay()
    {
        # 接收订单编号
        $orderNumber = input('post.order_number');
        # 接收支付类型(1:微信 2 ：支付宝3：银联 4：现金 银联支付 5：余额 现金支付 6：卡券 ,7:积分)
        $payType = input('post.pay_type');
        # 接收支付金额
        $payPrice = input('post.pay_price');
        # 接收用户的支付密码(余额支付时才有)
        $pwd = input('post.pwd');
        # 接收用户id
        $memberId = input('post.member_id');
        # 操作标识  mark===> fast 快速结算(有没完成的服务直接完成进行结算)
        $mark = input('post.mark');
        if (!empty($orderNumber) and !empty($payType) and !is_null($payPrice)) {
            # 添加订单支付状态(1=>支付中 2->支付成功 3->支付失败)
            $orderPayStatus = $this->_Redis->hGet('orderPayStatus', $orderNumber);
            if ($orderPayStatus == 2) {
                return array('status' => false, 'msg' => '该订单已经支付成功');
            }
            $this->_Redis->hSet('orderPayStatus', $orderNumber, 1);
            # 查询手机号
            $phone = Db::table('member')->field('member_phone')->where(array('id' => $memberId))->value('member_phone');
            # 判断支付类型进行收款
            switch (intval(trim($payType))) {
                case 1:
                    if (empty($pwd)) {
                        return array('status' => false, 'msg' => '请扫描微信收款码');
                    }
//                    $payPrice = 0.01;
                    # 微信支付(用户扫码)
                    /*$payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'body' => 'E联车服商家端服务支付',
                        'total_fee' => $payPrice * 100,
                        'attach' => json_encode(array('member_id' => $memberId, 'pay_price' => $payPrice))
                    ]);*/
                    /* # 用户收款码
                     $payment = new Payment([
                         'out_trade_no' => $orderNumber,
                         'body' => 'E联车服商家端服务支付',
                         'total_fee' => $payPrice * 100,
                         'auth_code' => $pwd,
                     ]);
                     $result = $payment->wxPay_pos();*/
                    if (in_array($phone, array('15840083826', '13066700403'))) {
                        $payPrice = 0.01;
                    }
                    $ordersPay = new OrdersPay();
                    $result = $ordersPay->WxPay('E联车服联盟', $orderNumber, $payPrice, $pwd);
                    break;
                case 2:
                    if (empty($pwd)) {
                        return array('status' => false, 'msg' => '请扫描支付宝收款码');
                    }
                    # 支付宝支付(用户扫码)
                    /*$payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'total_amount' => $payPrice,
                        'subject' => 'E联车服商家端服务支付',
                        'body' => json_encode(array('member_id' => $memberId, 'pay_price' => $payPrice))
                    ]);*/
//                    $payPrice = 0.01;
                    /*$payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'total_amount' => $payPrice,
                        'subject' => 'E联车服商家端服务支付',
                        'auth_code' => $pwd,
                    ]);
                    $result = $payment->aliPay_pos();*/
                    if (in_array($phone, array('15840083826', '13066700403'))) {
                        $payPrice = 0.01;
                    }
                    $ordersPay = new OrdersPay();
                    $result = $ordersPay->AliPay($orderNumber, $payPrice, $pwd);
                    break;
                case 5:
                    if (empty($memberId)) {
                        return array('status' => false, 'msg' => '未绑定用户,无法使用余额支付');
                    }
                    if (empty($pwd)) {
                        return array('status' => false, 'msg' => '请输入支付密码');
                    }
                    # 余额支付
                    $payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'pay_money' => $payPrice,
                        'auth_code' => $pwd,
                        'member_id' => $memberId,
                        'mark'=>input('post.mark')
                    ]);
                    $result = $payment->balancePay();
                    break;
                case 3:
                    # 银联支付
                    $payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'pay_money' => $payPrice,
                        'auth_code' => $pwd,
                        'member_id' => $memberId,
                    ]);
                    $result = $payment->paySuccess($orderNumber, 3, $payPrice);
                    break;
                case 4:
                    # 现金支付
                    $payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'pay_money' => $payPrice,
                        'auth_code' => $pwd,
                        'member_id' => $memberId,
                    ]);
                    $result = $payment->paySuccess($orderNumber, 4, $payPrice);
                    break;
                case 6:
                    if (empty($memberId)) {
                        return array('status' => false, 'msg' => '未绑定用户,无法使用卡券支付');
                    }
                    # 卡券id
                    $voucher_id = $pwd;
                    # 卡券信息
//                    $voucher_info = input('post.voucher_info');  or empty($voucher_info)
                    if (empty($voucher_id)) {
                        return array('status' => false, 'msg' => '请选择核销的卡券');
                    }
                    # 判断卡券是否可用
                    $VerificationVoucher = $this->VerificationVoucher($pwd, $orderNumber);
                    if (!$VerificationVoucher['status']) {
                        return $VerificationVoucher;
                    }
                    # 卡券支付
                    $payment = new Payment([
                        'out_trade_no' => $orderNumber,
                        'pay_money' => $payPrice,
                        'member_id' => $memberId,
                        'voucher_id' => $voucher_id,
                        'voucherInfo' => $VerificationVoucher['voucher']
                    ]);
                    $result = $payment->voucherPay();
                    break;
            }
            return $result;
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    function VerificationVoucher($voucherId, $orderNumber)
    {
        if (empty($orderNumber)) {
            return array('status' => false, 'msg' => '订单编号为空');
        }
        # 查询订单信息
        $orderInfo = Db::table('orders')->where(array('order_number' => $orderNumber))->find();
        if (empty($orderInfo) or empty($orderInfo['member_id'])) {
            return array('status' => false, 'msg' => '订单信息为空/未绑定用户');
        }
        if ($orderInfo['order_number'] == $voucherId) {
            if ($orderInfo['order_type'] == 3) {
                # 预约订单,使用订单编号核销
                # 卡券核销码相同,可以核销 , 将预约订单第一项改为已完成
                $order_server = Db::table('order_server')->field('id,status,is_appointment')->where(array('order_number' => $orderInfo['order_number']))->order(array('id' => 'asc'))->find();
                if (!empty($order_server)) {
                    if ($order_server['is_appointment'] == 2) {
                        return array('status' => false, 'msg' => '已经核销过了');
                    }
                    $voucherInfo = array();
                } else {
                    return array('status' => false, 'msg' => '工单信息为空');
                }
            } else {
                return array('status' => false, 'msg' => '不是预约订单');
            }
        } else {
            # 查询该车牌号今天是否用了卡券(用户端   合作端   相同一个车牌号一个合作店每天只能使用一个卡券)
            $useNum = Db::table('member_voucher')
                ->where("order_id in (select id from orders where biz_id = " . $this->bizId . " 
                and car_liences = '" . $orderInfo['car_liences'] . "' and date(order_create) = '" . date('Y-m-d') . "')")
                ->where(array('status' => 2))
                ->find();
            if (!empty($useNum)) {
                return array('status' => false, 'msg' => '今日暂无可用卡券');
            }
            # 查询该用户今天是否使用了现金卡券
            $cash_coupon = Db::table('log_cashcoupon lc')
                ->join('orders o','o.order_number=lc.order_number','left')
                ->where(array('lc.member_id' => $orderInfo['member_id'], 'lc.create_time' => date("Y-m-d"),'o.order_status'=>5))
                ->count('lc.id');
            # 查询用户可使用的卡券的条件 //and voucher_type != 11 and voucher_type != 12 and voucher_type != 13 and voucher_type != 14 and voucher_type != 15 and voucher_type != 16
            $voucherWhere = 'member_id = ' . $orderInfo['member_id'] . ' and status = 1 and `create` > "' . date('Y-m-d H:i:s') . '" and voucher_type != 7 and voucher_type != 8 and voucher_type != 9 and voucher_type != 10
          and voucher_type != 17 ';
            if ($cash_coupon > 0) {
                # 已经使用过现金抵值券,
//                return array('status' => false, 'msg' => '每天只可使用一次现金抵值券');
                $voucherWhere .= " and voucher_source != 4";
            }
            # 查用户卡券信息
            $voucherInfo = Db::table('member_voucher')->where(array('id' => $voucherId))->where($voucherWhere)->find();
//        var_dump(Db::table('member_voucher')->getLastSql());
            if (empty($voucherInfo)) {
                return array('status' => false, 'msg' => '每天只可使用一次现金抵值券');
            }
            # 订单总金额
            $orderCountPrice = floatval($orderInfo['order_price']) - floatval($orderInfo['voucher_price']);
            # 筛选可用的卡券
            # 查询该订单中是否存在商品
            $orderBizCount = Db::table('order_biz')->where(array('order_number' => $orderNumber, 'custommark' => 1, 'status' => 2))->count();
            # 查询用户的会员状态
            $memberLevelInfo = Db::table('member_mapping')->field(array('member_level_id', 'member_expiration'))->where(array('member_id' => $orderInfo['member_id']))->find();
            # 判断是不是会员
            if ($memberLevelInfo['member_level_id'] > 1) {
                # 等级会员
                $membership = $memberLevelInfo['member_level_id'];
            } elseif (($memberLevelInfo['member_level_id']) and $memberLevelInfo['member_expiration'] >= date('Y-m-d')) {
                # 体验卡会员
                $membership = 1;
            } else {
                # 不是会员
                $membership = 0;
            }
            if ($voucherInfo['voucher_id'] == 0) {
//                if($voucherInfo['voucher_source']==16){
//                    # 该卡券为现金红包
//                    $redPacketInfo = Db::table('redpacket_detail')->where("id = " . $voucherInfo['redpacket_id'] . " and voucher_id  =" . $voucherInfo['server_id'] . " and voucher_price = " . $voucherInfo['voucher_cost'] . "  and money_off <= " . $orderCountPrice)->find();
//                }else {
//                    # 该卡券为现金红包
//                    $redPacketInfo = Db::table('redpacket_detail')->where("redpacket_id = " . $voucherInfo['redpacket_id'] . " and voucher_id  =" . $voucherInfo['server_id'] . " and voucher_price = " . $voucherInfo['voucher_cost'] . "  and money_off <= " . $orderCountPrice)->find();
//                }
//                if (empty($redPacketInfo)) {
//                    # 卡券信息为空 , 去除该卡券信息
//                    return array('status' => false, 'msg' => '卡券信息为空,不可用');
//                }
                # 判断该订单下的工单中是否存在该卡券对应的服务
                if ($voucherInfo['voucher_type'] == 4) {
                    # 单独服务抵值券
                    $workOrderInfo = Db::table('order_server')
                        ->where(array('order_number' => $orderNumber, 'server_id' => $voucherInfo['server_id'], 'status' => 4, 'custommark' => 1))->count();
                    if ($workOrderInfo == 0) {
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                    }
                } elseif ($voucherInfo['voucher_type'] == 3) {
                    # 单独商品抵值券
                    $workOrderInfo = Db::table('order_biz')
                        ->where(array('order_number' => $orderNumber, 'biz_pro_id' => $voucherInfo['server_id'], 'status' => 2, 'custommark' => 1))->count();
                    if ($workOrderInfo == 0) {
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                    }
                } elseif ($voucherInfo['voucher_type'] == 1) {
                    # 商品通用抵值券
                    if ($orderBizCount == 0) {
                        # 去除该卡券信息
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                    }
                }
                $voucherInfo['voucher_title'] = $voucherInfo['card_title'];
                $voucherInfo['voucher_type_info'] = getTypeTitle($voucherInfo['voucher_type']);
                $voucherInfo['voucher_price'] = $voucherInfo['voucher_cost'];
                if ($voucherInfo['voucher_start'] == 2) {
                    # 1 可以当天使用  2 不可以当天使用
                    # 查询领取时间
                    $redLogTime = Db::table('redpacket_log')->field('date(`create_time`) create_time')
                        ->where(array('member_id' => $orderInfo['member_id'], 'redpacket_id' => $voucherInfo['redpacket_id']))
                        ->find();
                    if (!empty($redLogTime) and $redLogTime['create_time'] == date('Y-m-d')) {
                        # 去除该卡券信息(还没到卡券起始使用时间)
                        return array('status' => false, 'msg' => '该卡券未到使用时间');
                    }
                }
//                if ($redPacketInfo['useperson'] == 3) {
//                    # 所有会员,判断用户是不是会员,不是会员不能使用该卡券
//                    if ($membership == 0) {
//                        return array('status' => false, 'msg' => '非会员无法使用该卡券');
//                    }
//                } elseif ($redPacketInfo['useperson'] == -3) {
//                    # 所有非会员,如果用户是会员,则不能使用该卡券
//                    if ($membership > 0) {
//                        return array('status' => false, 'msg' => '会员用户无法使用该卡券');
//                    }
//                } elseif ($redPacketInfo['useperson'] == 4) {
//                    # 对应等级会员可以使用,判断用户是不是该卡券对应的会员等级
//                    if ($membership != $redPacketInfo['useperson_level']) {
//                        return array('status' => false, 'msg' => getLevel($redPacketInfo['useperson_level']) . '无法使用该卡券');
//                    }
//                }
            } else {
                if($voucherInfo['voucher_source']== 4 or  $voucherInfo['voucher_source']==14){
                    $biz_pid_where = '';
                }else{
                    # biz_pid != 0
                    $biz_pid_where = '';
                }
                # 普通获得方式,判断是否可以使用现金卡券
                if (in_array($voucherInfo['voucher_type'], array(11, 12, 13, 14, 15, 16))) {
                    $cardVoucherInfo = Db::table('merchants_voucher')->where(array('id' => $voucherInfo['voucher_id']))->find();
                    $cardVoucherInfo['card_type_id'] = $voucherInfo['voucher_type'];
                } else {
                    if ($cash_coupon > 0) {
                        # 使用了现金抵值券 , 不查现金抵值
                        $cardVoucherInfo = Db::table('card_voucher')->where("id = " . $voucherInfo['voucher_id'] . " and card_type_id != 2")->find();
                    } else {
                        $cardVoucherInfo = Db::table('card_voucher')->where(array('id' => $voucherInfo['voucher_id']))->find();
                    }
                }
                if (empty($cardVoucherInfo)) {
                    # 查询结果为空 , 去除该卡券信息
                    return array('status' => false, 'msg' => '每天只可使用一次现金抵值券');
                }
                if ($cardVoucherInfo['card_type_id'] == 1) {
                    # 判断该订单下的工单中是否存在该卡券对应的服务
                    $workOrderInfo = Db::table('order_server')
                        ->where(array('order_number' => $orderNumber, 'server_id' => $cardVoucherInfo['server_id'], 'status' => 4, 'custommark' => 1))->count();
                    if (empty($workOrderInfo)) {
                        # 去除该卡券信息
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                    }
                    $voucherInfo['voucher_type_info'] = '服务卡券';
                    $voucherInfo['voucher_title'] = $cardVoucherInfo['card_title'];
                    $voucherInfo['money_off'] = 0;
                    $voucherInfo['voucher_price'] = $cardVoucherInfo['card_price'];
                } elseif ($cardVoucherInfo['card_type_id'] == 2) {
                    $voucherInfo['voucher_type_info'] = '现金抵值券';
                    $voucherInfo['voucher_title'] = $cardVoucherInfo['card_title'];
                    $voucherInfo['money_off'] = 0;
                    $voucherInfo['voucher_price'] = $cardVoucherInfo['card_price'];
                } elseif ($cardVoucherInfo['card_type_id'] == 3) {
                    # 判断该订单下的工单中是否存在该卡券对应的商品
                    $workOrderInfo = Db::table('order_biz')
                        ->where(array('order_number' => $orderNumber, 'biz_pro_id' => $cardVoucherInfo['server_id'], 'status' => 2, 'custommark' => 1))->count();
                    if (empty($workOrderInfo)) {
                        # 去除该卡券信息
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                    }
                    $voucherInfo['voucher_type_info'] = '商品卡券';
                    $voucherInfo['voucher_title'] = $cardVoucherInfo['card_title'];
                    $voucherInfo['money_off'] = 0;
                    $voucherInfo['voucher_price'] = $cardVoucherInfo['card_price'];
                } elseif ($cardVoucherInfo['card_type_id'] == 11 or $cardVoucherInfo['card_type_id'] == 12 or $cardVoucherInfo['card_type_id'] == 13) {
                    if ($cardVoucherInfo['card_type_id'] == 11) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(服务通用 门店创建的服务)
                        $add_type = "add_type = 2";
                        $voucher_type_info = '服务通用抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 12) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(商品通用 门店创建的商品)
                        $add_type = "add_type = 1";
                        $voucher_type_info = '商品通用抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 13) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(全部通用 门店创建的商品/服务)
                        $add_type = "";
                        $voucher_type_info = '全部通用抵用券';
                    }
                    $workOrderInfo = Db::table('service')
                        ->where($add_type)
                        ->where($biz_pid_where)
                        ->where("audit_status = 2 and service_status = 1")
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 1)")
                        ->count();
                    if (!empty($workOrderInfo)) {
                        $voucherInfo['voucher_title'] = $cardVoucherInfo['title'];
                        $voucherInfo['voucher_type_info'] = $voucher_type_info;
                        $voucherInfo['money_off'] = $cardVoucherInfo['min_consume'];
                        $voucherInfo['voucher_price'] = $cardVoucherInfo['price'];
                    } else {
                        # 去除该卡券信息
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务-');
                    }
                } elseif ($cardVoucherInfo['card_type_id'] == 14 or $cardVoucherInfo['card_type_id'] == 15 or $cardVoucherInfo['card_type_id'] == 16) {
                    # 14 服务分类抵用券 15商品分类抵用券(门店创建的商品) 16全部分类抵用券
                    if (empty($cardVoucherInfo['second_cate_pid'])) {
                        # 二级分类为空
                        $classInfo = Db::table('service_class')->field('id')->where('service_class_pid = ' . $cardVoucherInfo['cate_pid'] . ' or id = ' . $cardVoucherInfo['cate_pid'])->select();
                        $classInfo = implode(',', array_column($classInfo, 'id'));
                        $class_where = " service_class_id in (" . $classInfo . ")";
                        $class_where_cus = " custom_server_class in (" . $classInfo . ")";
                    } else {
                        # 二级分类不为空
                        $class_where = " service_class_id = " . $cardVoucherInfo['second_cate_pid'];
                        $class_where_cus = " custom_server_class = " . $cardVoucherInfo['second_cate_pid'];
                    }
                    $add_type = '';
                    if ($cardVoucherInfo['card_type_id'] == 14) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(服务分类)
                        $voucher_type_info = '服务分类抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 15) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(商品分类 门店创建的商品)
                        $add_type = "add_type = 1";
                        $voucher_type_info = '商品分类抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 16) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(全部分类)
                        $voucher_type_info = '全部分类抵用券';
                    }
                    $workOrderInfo = Db::table('service')
                        ->where($add_type)
                        ->where($class_where)
                        ->where($biz_pid_where)
                        ->where("audit_status = 2 and service_status = 1")
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 1)")
                        ->count();
                    $workOrderInfo_cus = Db::table('customserver')
                        ->where($class_where_cus)
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 2)")
                        ->count();
                    if (!empty($workOrderInfo) or !empty($workOrderInfo_cus)) {
                        $voucherInfo['voucher_title'] = $cardVoucherInfo['title'];
                        $voucherInfo['voucher_type_info'] = $voucher_type_info;
                        $voucherInfo['money_off'] = $cardVoucherInfo['min_consume'];
                        $voucherInfo['voucher_price'] = $cardVoucherInfo['price'];
                    } else {
                        # 去除该卡券信息
                        return array('status' => false, 'msg' => '该订单无卡券对应的服务--');
                    }

                } else {
                    # 去除该卡券信息
                    return array('status' => false, 'msg' => '该订单无卡券对应的服务');
                }
            }
        }
        return array('status' => true, 'voucher' => $voucherInfo);
    }

    /**
     * @return array
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 查询订单支付状态
     */
    function findOrderStatus()
    {
        # 订单编号
        $orderNumber = input('post.order_number');
        # 支付方式
        $payType = input('post.pay_type');
        # 支付价格
        $pay_price = input('post.pay_price');
        if (!empty($orderNumber)) {
            /*if ($payType == 1) {
                # 微信
                $mark = 'wx';
            } else {
                # 支付宝
                $mark = 'zfb';
            }
            $payment = new Payment([
                'out_trade_no' => $orderNumber,
                'payment' => $mark
            ]);
            $res = $payment->findOrderStatus();
            if ($res['status'] and $res['code'] == 'SUCCESS') {
                # 支付成功,修改订单支付状态为支付成功(1->支付中  2->支付成功 3->支付失败)
                $this->_Redis->hSet('orderPayStatus', $orderNumber, 2);
                # 支付成功
                $payment = new Payment();
                $payment->paySuccess($orderNumber, $payType, $pay_price);
            }
            return $res;*/
            $ordersPay = new OrdersPay();
            $redis = new Redis();
            $redis->hSetJson('payRedis' . $this->bizId, $orderNumber, array('payType' => $payType, 'payPrice' => $pay_price, 'time' => date('Y-m-d H:i:s')));
            $result = $ordersPay->OrderStatusQuery($orderNumber, $payType, $pay_price);
            return $result;
        } else {
            return array('status' => false, 'msg' => '订单编号为空');
        }
    }



    /**
     * @return array
     * @content 查询订单支付状态
     */
//    function findOrderStatus()
//    {
//        # 接收订单编号
//        $orderNumber = input('post.order_number');
//        if (!empty($orderNumber)) {
//            $redis = new Redis();
//            # 查询订单状态
//            $orderStatus = $redis->hGet('orderPayStatus', $orderNumber);
//            if ($orderStatus == 1) {
//                $msg = '支付中';
//            } elseif ($orderStatus == 2) {
//                $msg = '支付成功';
//            } else {
//                $msg = '支付失败';
//            }
//            return array('status' => true, 'msg' => $msg, 'orderStatus' => $orderStatus);
//        } else {
//            return array('status' => false, 'msg' => '订单编号为空');
//        }
//    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询用户该订单是否有可使用的卡券信息
     */
    function voucherInfo()
    {
        # 接收订单编号
        $orderNumber = input('post.order_number');
        if (empty($orderNumber)) {
            return array('status' => false, 'msg' => '订单编号为空');
        }
        # 查询订单信息
        $orderInfo = Db::table('orders')->field('id,member_id,order_price,voucher_price,order_type,order_status,car_liences')->where(array('order_number' => $orderNumber))->find();
        if (empty($orderInfo) or empty($orderInfo['member_id'])) {
            return array('status' => false, 'msg' => '订单信息为空/未绑定用户');
        }
        #判断是否有预约订单
        if ($orderInfo['order_type'] == 3 and $orderInfo['order_status'] != 5) {
            # 判断预约的是否被核销,核销掉之后不能在使用卡券
            $orderServer = Db::table('order_server')
                ->field('status,is_appointment')
                ->where(array('order_number' => $orderNumber))
                ->order('id asc')
                ->find();
            if ($orderServer['is_appointment'] == 2) {
                return array('status' => false, 'msg' => '暂无可用卡券');
            }
            return array('status' => true, 'voucher' => array('order_number' => $orderNumber), 'msg' => '预约订单');
        }
        # 查询该车牌号今天是否用了卡券(用户端   合作端   相同一个车牌号一个合作店每天只能使用一个卡券)
        $useNum = Db::table('member_voucher')
            ->where("order_id in (select id from orders where biz_id = " . $this->bizId . " and car_liences = '" . $orderInfo['car_liences'] . "' and date(order_create) = '" . date('Y-m-d') . "')")
            ->where(array('status' => 2))
            ->find();
        if (!empty($useNum)) {
            return array('status' => false, 'msg' => '今日暂无可用卡券');
        }
        # 查询该用户今天是否使用了现金卡券
        $cash_coupon = Db::table('log_cashcoupon lc')
            ->join('orders o','o.order_number=lc.order_number','left')
            ->where(array('lc.member_id' => $orderInfo['member_id'], 'lc.create_time' => date("Y-m-d"),'o.order_status'=>5))
            ->count('lc.id');
        # 查询用户可使用的卡券的条件 //and voucher_type != 11 and voucher_type != 12 and voucher_type != 13 and voucher_type != 14 and voucher_type != 15 and voucher_type != 16
        $voucherWhere = 'member_id = ' . $orderInfo['member_id'] . ' and status = 1 and `create` > "' . date('Y-m-d H:i:s') . '" and voucher_type != 7 and voucher_type != 8 and voucher_type != 9 and voucher_type != 10
          and voucher_type != 17 ';
        if ($cash_coupon > 0) {
//            return array('status' => false, 'msg' => '暂无可用卡券');
            # 已经使用过现金抵值券,
            $voucherWhere .= " and voucher_source != 4";
        }
        # 订单总金额
        $orderCountPrice = floatval($orderInfo['order_price']) - floatval($orderInfo['voucher_price']);
        # 查用户卡券信息   ->where("money_off <= ".$orderCountPrice)
        $voucherInfo = Db::table('member_voucher')->where($voucherWhere)->select();
        if (empty($voucherInfo)) {
            return array('status' => false, 'msg' => '卡券列表为空,暂无可用卡券');
        }
        # 查询这个订单是否使用了卡券,每个订单只能使用一次卡券
        $logVoucherOrder = Db::table('log_cashcoupon')
            ->where(array('order_number' => $orderNumber))->count();
        if ($logVoucherOrder > 0) {
            return array('status' => false, 'msg' => '暂无可用卡券');
        }
        # 筛选可用的卡券
        # 查询该订单中是否存在商品
        $orderBizCount = Db::table('order_biz')->where(array('order_number' => $orderNumber, 'custommark' => 1, 'status' => 2))->count();
        # 查询用户的会员状态
        $memberLevelInfo = Db::table('member_mapping')->field('member_level_id,member_expiration expiration')->where(array('member_id' => $orderInfo['member_id']))->find();
        # 判断是不是会员
        if ($memberLevelInfo['member_level_id'] > 1) {
            # 等级会员
            $membership = $memberLevelInfo['member_level_id'];
        } elseif (($memberLevelInfo['member_level_id'] == 1) and $memberLevelInfo['expiration'] >= date('Y-m-d')) {
            # 体验卡会员
            $membership = 1;
        } else {
            # 不是会员
            $membership = 0;
        }
        foreach ($voucherInfo as $k => $v) {
            if($v['voucher_source']== 4 or  $v['voucher_source']==14){
                $biz_pid_where = '';
            }else{
                $biz_pid_where = 'biz_pid != 0';
            }
            if ($v['redpacket_id'] != 0) {
                $voucherInfo[$k]['voucher_title'] = $v['card_title'];
                $voucherInfo[$k]['voucher_type_info'] = getTypeTitle($v['voucher_type']);
                $voucherInfo[$k]['money_off'] = $v['money_off'];
                $voucherInfo[$k]['voucher_price'] = $v['voucher_cost'];
//                # 该卡券为现金红包
//                $redPacketInfo = Db::table('redpacket_detail')->where("id = " . $v['redpacket_id'] . " and money_off <= " . $orderCountPrice)->find();
//                if (empty($redPacketInfo)) {
//                    # 卡券信息为空 , 去除该卡券信息
//                    unset($voucherInfo[$k]);
//                }
                if ($v['voucher_start'] == 2) {
                    # 1 可以当天使用  2 不可以当天使用
//                    # 查询领取时间
//                    $redLogTime = Db::table('redpacket_log')->field('date(`create_time`) create_time')
//                        ->where(array('member_id' => $orderInfo['member_id'], 'redpacket_id' => $v['redpacket_id']))
//                        ->find();
                    if (date('Y-m-d', strtotime($v['start_time'])) == date('Y-m-d')) {
                        # 去除该卡券信息(还没到卡券起始使用时间)
                        unset($voucherInfo[$k]);
                    }
                }
                # 判断该订单下的工单中是否存在该卡券对应的服务
                if ($v['voucher_type'] == 4) {
                    # 单独服务抵值券
                    $workOrderInfo = Db::table('order_server')
                        ->where(array('order_number' => $orderNumber, 'server_id' => $v['server_id'], 'status' => 4, 'custommark' => 1))->count();
                    if ($workOrderInfo == 0) {
                        unset($voucherInfo[$k]);
                    } else {
                        continue;
                    }
                } elseif ($v['voucher_type'] == 3) {
                    # 单独商品抵值券
                    $workOrderInfo = Db::table('order_biz')
                        ->where(array('order_number' => $orderNumber, 'biz_pro_id' => $v['server_id'], 'status' => 2, 'custommark' => 1))->count();
                    if ($workOrderInfo == 0) {
                        unset($voucherInfo[$k]);
                    } else {
                        continue;
                    }
                } elseif ($v['voucher_type'] == 1) {
                    # 商品通用抵值券
                    if ($orderBizCount == 0) {
                        # 去除该卡券信息
                        unset($voucherInfo[$k]);
                    }
                }

                if ($v['money_off'] > 0 and $v['money_off'] > $orderCountPrice) {
                    unset($voucherInfo[$k]);
                }
                /*if ($v['useperson'] == 3) {
                    # 所有会员,判断用户是不是会员,不是会员不能使用该卡券
                    if ($membership == 0) {
                        unset($voucherInfo[$k]);
                    }
                } elseif ($v['useperson'] == -3) {
                    # 所有非会员,如果用户是会员,则不能使用该卡券
                    if ($membership > 0) {
                        unset($voucherInfo[$k]);
                    }
                } elseif ($v['useperson'] == 4) {
                    # 对应等级会员可以使用,判断用户是不是该卡券对应的会员等级
                    if ($membership != $v['useperson_level']) {
                        unset($voucherInfo[$k]);
                    }
                }*/
            } else {
                # 普通获得方式,判断是否可以使用现金卡券
                if (in_array($v['voucher_type'], array(11, 12, 13, 14, 15, 16))) {
                    $cardVoucherInfo = Db::table('merchants_voucher')->where(array('id' => $v['voucher_id']))->find();
                    $cardVoucherInfo['card_type_id'] = $v['voucher_type'];
                } else {
                    if ($cash_coupon > 0) {
                        # 使用了现金抵值券 , 不查现金抵值
                        $cardVoucherInfo = Db::table('card_voucher')->where("id = " . $v['voucher_id'] . " and card_type_id != 2")->find();
                    } else {
                        $cardVoucherInfo = Db::table('card_voucher')->where(array('id' => $v['voucher_id']))->find();
                    }
                }
                if (empty($cardVoucherInfo)) {
                    # 查询结果为空 , 去除该卡券信息
                    unset($voucherInfo[$k]);
                }
                if ($cardVoucherInfo['card_type_id'] == 1) {
                    # 判断该订单下的工单中是否存在该卡券对应的服务
                    $workOrderInfo = Db::table('order_server')
                        ->where(array('order_number' => $orderNumber, 'server_id' => $cardVoucherInfo['server_id'], 'status' => 4, 'custommark' => 1))->count();
                    if (!empty($workOrderInfo)) {
                        $voucherInfo[$k]['voucher_title'] = $cardVoucherInfo['card_title'];
                        $voucherInfo[$k]['voucher_type_info'] = '服务卡券';
                        $voucherInfo[$k]['money_off'] = 0;
                        $voucherInfo[$k]['voucher_price'] = $cardVoucherInfo['card_price'];
                    } else {
                        # 去除该卡券信息
                        unset($voucherInfo[$k]);
                    }
                } elseif ($cardVoucherInfo['card_type_id'] == 2) {
                    $voucherInfo[$k]['voucher_title'] = $cardVoucherInfo['card_title'];
                    $voucherInfo[$k]['voucher_type_info'] = '现金抵值券';
                    $voucherInfo[$k]['money_off'] = 0;
                    $voucherInfo[$k]['voucher_price'] = $cardVoucherInfo['card_price'];
                } elseif ($cardVoucherInfo['card_type_id'] == 3) {
                    # 判断该订单下的工单中是否存在该卡券对应的商品
                    $workOrderInfo = Db::table('order_biz')
                        ->where(array('order_number' => $orderNumber, 'biz_pro_id' => $cardVoucherInfo['server_id'], 'status' => 2, 'custommark' => 1))->count();
                    if (!empty($workOrderInfo)) {
                        $voucherInfo[$k]['voucher_title'] = $cardVoucherInfo['card_title'];
                        $voucherInfo[$k]['voucher_type_info'] = '商品卡券';
                        $voucherInfo[$k]['money_off'] = 0;
                        $voucherInfo[$k]['voucher_price'] = $cardVoucherInfo['card_price'];
                    } else {
                        # 去除该卡券信息
                        unset($voucherInfo[$k]);
                    }
                } elseif ($cardVoucherInfo['card_type_id'] == 11 or $cardVoucherInfo['card_type_id'] == 12 or $cardVoucherInfo['card_type_id'] == 13) {
                    if ($cardVoucherInfo['card_type_id'] == 11) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(服务通用 门店创建的服务)
                        $add_type = "add_type = 2";
                        $voucher_type_info = '服务通用抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 12) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(商品通用 门店创建的商品)
                        $add_type = "add_type = 1";
                        $voucher_type_info = '商品通用抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 13) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(全部通用 门店创建的商品/服务)
                        $add_type = "";
                        $voucher_type_info = '全部通用抵用券';
                    }else{
                        $add_type = '';
                    }
                    $workOrderInfo = Db::table('service')
                        ->where($add_type)
                        ->where($biz_pid_where)
                        ->where("audit_status = 2 and service_status = 1")
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 1)")
                        ->count();
                    if (!empty($workOrderInfo)) {
                        $voucherInfo[$k]['voucher_title'] = $cardVoucherInfo['title'];
                        $voucherInfo[$k]['voucher_type_info'] = $voucher_type_info;
                        $voucherInfo[$k]['money_off'] = $cardVoucherInfo['min_consume'];
                        $voucherInfo[$k]['voucher_price'] = $cardVoucherInfo['price'];
                    } else {
                        # 去除该卡券信息
                        unset($voucherInfo[$k]);
                    }
                } elseif ($cardVoucherInfo['card_type_id'] == 14 or $cardVoucherInfo['card_type_id'] == 15 or $cardVoucherInfo['card_type_id'] == 16) {
                    # 14 服务分类抵用券 15商品分类抵用券(门店创建的商品) 16全部分类抵用券
                    if (empty($cardVoucherInfo['second_cate_pid'])) {
                        # 二级分类为空
                        $classInfo = Db::table('service_class')->field('id')->where('service_class_pid = ' . $cardVoucherInfo['cate_pid'] . ' or id = ' . $cardVoucherInfo['cate_pid'])->select();
                        $classInfo = implode(',', array_column($classInfo, 'id'));
                        $class_where = " service_class_id in (" . $classInfo . ")";
                        $class_where_cus = " custom_server_class in (" . $classInfo . ")";
                    } else {
                        # 二级分类不为空
                        $class_where = " service_class_id = " . $cardVoucherInfo['second_cate_pid'];
                        $class_where_cus = " custom_server_class = " . $cardVoucherInfo['second_cate_pid'];
                    }
                    $add_type = '';
                    if ($cardVoucherInfo['card_type_id'] == 14) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(服务分类)
                        $voucher_type_info = '服务分类抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 15) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(商品分类 门店创建的商品)
                        $add_type = "add_type = 1";
                        $voucher_type_info = '商品分类抵用券';
                    } elseif ($cardVoucherInfo['card_type_id'] == 16) {
                        # 判断该订单下的工单中是否存在该卡券对应的服务(全部分类)
                        $voucher_type_info = '全部分类抵用券';
                    }
                    $workOrderInfo = Db::table('service')
                        ->where($add_type)
                        ->where($class_where)
                        ->where($biz_pid_where)
                        ->where("audit_status = 2 and service_status = 1")
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 1)")
                        ->count();
                    $workOrderInfo_cus = Db::table('customserver')
                        ->where($class_where_cus)
                        ->where(" id in (select server_id from order_server where order_number = '" . $orderNumber . "' and status = 4 and custommark = 2)")
                        ->count();
                    if (!empty($workOrderInfo) or !empty($workOrderInfo_cus)) {
                        $voucherInfo[$k]['voucher_title'] = $cardVoucherInfo['title'];
                        $voucherInfo[$k]['voucher_type_info'] = $voucher_type_info;
                        $voucherInfo[$k]['money_off'] = $cardVoucherInfo['min_consume'];
                        $voucherInfo[$k]['voucher_price'] = $cardVoucherInfo['price'];
                    } else {
                        # 去除该卡券信息
                        unset($voucherInfo[$k]);
                    }

                } else {
                    # 去除该卡券信息
                    unset($voucherInfo[$k]);
                }
            }
        }
        if (!empty($voucherInfo)) {
            return array('status' => true, 'voucher' => $voucherInfo, 'msg' => '卡券列表');
        } else {
            # 筛选后,没有可用卡券
            #判断是否有预约订单
            if ($orderInfo['order_type'] == 3 and $orderInfo['order_status'] != 5) {
                return array('status' => true, 'voucher' => array('order_number' => $orderNumber), 'msg' => '预约订单');
            }
            return array('status' => false, 'msg' => '暂无可用卡券');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 快速结账--查询会员信息
     */
    function findPhone()
    {
        # 手机号
        $phone = input('post.phone');
        if (empty($phone) or !CheckMobile($phone)) {
            return array('status' => false, 'msg' => '手机号格式不正确');
        }
        # 查询用户信息
        $memberInfo = Db::table('member m')
            ->field('m.id,m.member_phone,m.member_name,m.nickname,m.headimage,m.toutiao_name,m.toutiao_head,mm.member_level_id,mm.member_code,mm.member_expiration')
            ->join('member_mapping mm', 'm.id=mm.member_id', 'left')
            ->where(array('m.member_phone' => $phone))
            ->where("mm.member_code != ''")
//            ->where("mm.member_level_id > 1 or (mm.member_level_id = 1 and mm.member_expiration > '" . date('Y-m-d') . "')")
            ->find();
        if (empty($memberInfo)) {
            return array('status' => false, 'msg' => '该用户未注册,无法快速结算');
        }
        # 查询是否存在订单
        $orders = Db::table('orders')
            ->where(array('member_id'=>$memberInfo['id'],'biz_id'=>$this->bizId))
            ->where("order_status = 1 or order_status = 6")
            ->count();
        if($orders > 0){
            return array('status' => false, 'msg' => '已存在订单,无法使用快速结算');
        }
        # 会员姓名昵称信息 判断
        if (empty($memberInfo['member_name'])) {
            $memberInfo['member_name'] = $memberInfo['toutiao_name'];
        }
        if (empty($memberInfo['nickname'])) {
            $memberInfo['nickname'] = $memberInfo['toutiao_name'];
        } else {
            $memberInfo['member_name'] = $memberInfo['nickname'];
        }

        if (empty($memberInfo['headimage'])) {
            $memberInfo['headimage'] = $memberInfo['toutiao_head'];
        }
        # 查询会员信息名称
        if($memberInfo['member_level_id'] == 1 and $memberInfo['member_expiration'] < date('Y-m-d')){
            $memberInfo['member_level_id'] = 0;
        }
        $memberInfo['level_title'] = Db::table('member_level')->where(array('id' => $memberInfo['member_level_id']))->value('level_title');
        if(empty($memberInfo['level_title'])){
            $memberInfo['level_title'] = '普通用户';
        }
        # 查询该用户的车辆信息
        $carInfo = Db::table('member_car mc')
            ->field("mc.*,cl.title logo_title,cs.sort_title,cle.level_title,cs.level,cs.logo_id,
                date_format( mc.register_time,'%Y.%m.%d %H:%i:%s') login_time")
            ->join('car_sort cs', 'cs.id = mc.car_type_id')
            ->join('car_logo cl', 'cl.id = cs.logo_id')
            ->join('car_level cle', 'cle.id = cs.level')
            ->where("mc.member_id = " . $memberInfo['id'])
            ->where("mc.status != 3")
            ->order('id desc')
            ->find();
        if (empty($carInfo)) {
            # 没车
            $hasCar = 2;
        } else {
            # 有车
            $hasCar = 1;
            # 车辆名称信息拼接
            $carInfo['title_info'] = $carInfo['logo_title'] . '·' . $carInfo['sort_title'] . "(" . $carInfo['level_title'] . ")";
        }
        return array('status' => true, 'memberInfo' => $memberInfo, 'carInfo' => $carInfo, 'hasCar' => $hasCar);
    }

    function modifyCarInfoFast()
    {
        # 车辆 logo信息
        $logoInfo = input('post.logo_info');
        if (empty($logoInfo)) {
            return array('status' => false, 'msg' => '系统错误,品牌信息为空');
        }
        # 车辆 sort信息
        $sortInfo = input('post.sort_info');
        if (empty($sortInfo)) {
            return array('status' => false, 'msg' => '系统错误,系别信息为空');
        }
        # 车牌 信息
        $car_info = input('post.car_info');
        if (empty($car_info)) {
            return array('status' => false, 'msg' => '系统错误,车牌信息为空');
        }
        # 用户id
        $memberId = input('post.member_id');
        if (empty($memberId)) {
            return array('status' => false, 'msg' => '系统错误,用户信息为空');
        }
        # 查询用户车辆信息,为空添加  不为空修改
        $carInfo = Db::table('member_car')->field('id')
            ->where(array('member_id' => $memberId))
            ->where("status != 3")
            ->order('id desc')->find();
        if (!empty($carInfo)) {
            # 修改
            Db::table('member_car')->where(array('id' => $carInfo['id']))
                ->update(array('car_type_id' => $sortInfo['sort_id']));
        } else {
            # 添加
            Db::table('member_car')
                ->insert(array(
                    'car_licens' => $car_info['car_licens'],
                    'car_type_id' => $sortInfo['sort_id'],
                    'member_id' => $memberId,
                    'status' => 1,
                    'create_time' => date('Y-m-d H:i:s')
                ));
        }
        # 查询该用户的车辆信息
        $carInfo = Db::table('member_car mc')
            ->field("mc.*,cl.title logo_title,cs.sort_title,cle.level_title,cs.level,cs.logo_id,
                date_format( mc.register_time,'%Y.%m.%d %H:%i:%s') login_time")
            ->join('car_sort cs', 'cs.id = mc.car_type_id')
            ->join('car_logo cl', 'cl.id = cs.logo_id')
            ->join('car_level cle', 'cle.id = cs.level')
            ->where("mc.member_id = " . $memberId)
            ->where("mc.status != 3")
            ->order('id desc')
            ->find();
        if (empty($carInfo)) {
            # 没车
            $hasCar = 2;
        } else {
            # 有车
            $hasCar = 1;
            # 车辆名称信息拼接
            $carInfo['title_info'] = $carInfo['logo_title'] . '·' . $carInfo['sort_title'] . "(" . $carInfo['level_title'] . ")";
        }
        return array('status' => true, 'carInfo' => $carInfo, 'hasCar' => $hasCar);

    }
}
